# -*- coding: utf-8 -*-
"""
CLI命令行接口主模块
使用Click框架实现用户友好的命令行界面
"""
import os
import sys

import click

# 确保正确的导入路径
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
if parent_dir not in sys.path:
    sys.path.insert(0, parent_dir)

from core.detector import DuplicateDetector
from core.db_detector import DatabaseDuplicateDetector
from core.reporter import ReportGenerator
from utils.file_handler import FileHandler


@click.group()
@click.version_option(version='2.0.0', prog_name='视频重复检测工具')
def cli():
    """
    视频文件重复检测工具 (V2)
    
    支持FC2、有码、无码三种类型的视频文件重复检测
    """
    pass


@cli.command()
@click.argument('input_file', type=click.Path(exists=True))
@click.option('--output', '-o', type=click.Path(), help='输出报告文件路径')
@click.option('--use-database', is_flag=True, help='使用数据库对比模式检测重复')
@click.option('--insert-new', is_flag=True, help='将不重复的新番号插入到数据库（仅在--use-database时有效）')
@click.option('--db-path', type=click.Path(), help='数据库文件路径', default='duplicate_checker.db')
def check_single(input_file: str, output: str, use_database: bool, insert_new: bool, db_path: str):
    """
    检查单个文件中的重复项
    
    INPUT_FILE: 包含视频文件名的文本文件路径
    """
    try:
        file_handler = FileHandler()
        filenames = file_handler.read_file_list(input_file)

        if not filenames:
            click.echo("❌ 文件为空或读取失败", err=True)
            return

        click.echo(f"📂 正在分析文件: {input_file}")
        click.echo(f"📊 总文件数: {len(filenames)}")

        if use_database:
            click.echo(f"🗃️  使用数据库: {db_path}")
            if insert_new:
                click.echo("✅ 启用数据库插入模式")

            with DatabaseDuplicateDetector(db_path) as db_detector:
                result = db_detector.check_against_database(filenames, insert_new)

                reporter = ReportGenerator()
                report = reporter.generate_database_check_report(result, os.path.basename(input_file))

                if output:
                    with open(output, 'w', encoding='utf-8') as f:
                        f.write(report)
                    click.echo(f"\n📄 报告已保存到: {output}")
                else:
                    click.echo("\n" + report)

                # 显示快速总结 (V2)
                click.echo("\n📈 快速总结")
                click.echo("-" * 40)
                if result['comparison_results']:
                    click.echo(f"🔍 发现 {len(result['comparison_results'])} 个重复番号 (详情见报告)")
                if result['new_videos']:
                    click.echo(f"🆕 发现 {len(result['new_videos'])} 个新番号")
                    if insert_new:
                        click.echo(f"  ✅ 成功插入: {result['insert_success']} 个")
                        if result['insert_failed'] > 0:
                            click.echo(f"  ❌ 插入失败: {result['insert_failed']} 个")
                if result['dirty_files'] > 0:
                    click.echo(f"⚠️  发现 {result['dirty_files']} 个脏数据文件")

        else:
            # 传统内存重复检测
            detector = DuplicateDetector()
            result = detector.detect_single_file_duplicates(filenames)

            reporter = ReportGenerator()
            report = reporter.generate_single_file_report(result, os.path.basename(input_file))

            if output:
                with open(output, 'w', encoding='utf-8') as f:
                    f.write(report)
                click.echo(f"\n📄 报告已保存到: {output}")
            else:
                click.echo("\n" + report)

            stats = result['stats']
            if result['duplicates']:
                click.echo(f"\n⚠️  发现 {stats['duplicate_groups']} 组重复，涉及 {stats['duplicate_files']} 个文件")
            else:
                click.echo("\n✅ 未发现重复文件")

            if result['dirty_files'] > 0:
                click.echo(f"⚠️  发现 {result['dirty_files']} 个脏数据文件")

    except Exception as e:
        click.echo(f"❌ 执行失败: {str(e)}", err=True)
        print(e)


# --- 其他命令保持不变 ---
@cli.command()
@click.argument('file1', type=click.Path(exists=True))
@click.argument('file2', type=click.Path(exists=True))
@click.option('--output', '-o', type=click.Path(), help='输出报告文件路径')
def check_cross(file1: str, file2: str, output: str):
    """检查两个文件之间的重复项"""
    try:
        file_handler = FileHandler()
        file1_names = file_handler.read_file_list(file1)
        file2_names = file_handler.read_file_list(file2)

        if not file1_names or not file2_names:
            click.echo("❌ 文件为空或读取失败", err=True)
            return

        detector = DuplicateDetector()
        result = detector.detect_cross_file_duplicates(file1_names, file2_names)

        reporter = ReportGenerator()
        report = reporter.generate_cross_file_report(
            result,
            os.path.basename(file1),
            os.path.basename(file2)
        )

        if output:
            with open(output, 'w', encoding='utf-8') as f:
                f.write(report)
            click.echo(f"\n📄 报告已保存到: {output}")
        else:
            click.echo("\n" + report)

    except Exception as e:
        click.echo(f"❌ 执行失败: {str(e)}", err=True)


@cli.command()
@click.argument('prefix')
def add_prefix(prefix: str):
    """添加新的无码特殊前缀"""
    try:
        detector = DuplicateDetector()
        detector.parser.add_uncensored_prefix(prefix.upper())
        click.echo(f"✅ 已添加新的无码前缀: {prefix.upper()}")

        current_prefixes = detector.parser.config.UNCENSORED_PREFIXES
        click.echo(f"📋 当前支持的无码前缀: {', '.join(current_prefixes)}")

    except Exception as e:
        click.echo(f"❌ 添加失败: {str(e)}", err=True)


@cli.command()
def list_prefixes():
    """列出当前支持的所有无码特殊前缀"""
    try:
        detector = DuplicateDetector()
        prefixes = detector.parser.config.UNCENSORED_PREFIXES
        click.echo("📋 当前支持的无码特殊前缀:")
        for i, prefix in enumerate(prefixes, 1):
            click.echo(f"  {i:2d}. {prefix}")

    except Exception as e:
        click.echo(f"❌ 获取失败: {str(e)}", err=True)


@cli.command()
@click.argument('test_filename')
def test_parse(test_filename: str):
    """测试解析单个文件名"""
    try:
        detector = DuplicateDetector()
        video_info = detector.parser.parse(test_filename)

        click.echo(f"🔍 解析结果: {test_filename}")
        click.echo(f"   类型: {video_info.video_type.value}")
        click.echo(f"   核心ID: {video_info.clean_core_id}")

        attrs = []
        if video_info.has_4k: attrs.append("4K")
        if video_info.has_subtitle: attrs.append("字幕")
        if video_info.has_leak: attrs.append("流出")
        if video_info.is_segment: attrs.append(f"分段CD{video_info.segment_number}")
        if attrs:
            click.echo(f"   属性: {', '.join(attrs)}")

        if video_info.is_dirty:
            click.echo(f"   ⚠️  脏数据: {video_info.error_reason}")

    except Exception as e:
        click.echo(f"❌ 解析失败: {str(e)}", err=True)


@click.group()
def db():
    """数据库管理命令"""
    pass


@db.command()
@click.option('--db-path', type=click.Path(), help='数据库文件路径', default='duplicate_checker.db')
def init(db_path: str):
    """初始化数据库"""
    try:
        DatabaseDuplicateDetector(db_path).close()
        click.echo(f"✅ 数据库初始化完成: {db_path}")
    except Exception as e:
        click.echo(f"❌ 数据库初始化失败: {str(e)}", err=True)


@db.command()
@click.option('--db-path', type=click.Path(), help='数据库文件路径', default='duplicate_checker.db')
def stats(db_path: str):
    """显示数据库统计信息"""
    try:
        with DatabaseDuplicateDetector(db_path) as db_detector:
            stats = db_detector.get_database_statistics()

        click.echo("📊 数据库统计信息")
        click.echo("-" * 40)
        click.echo(f"总记录数: {stats['total_records']}")
        click.echo(f"有效记录数: {stats['clean_records']}")
        click.echo(f"最新添加时间: {stats.get('latest_added', '无')}")

        type_names = {'fc2': 'FC2', 'censored': '有码', 'uncensored': '无码'}
        type_dist = stats.get('type_distribution', {})
        if type_dist:
            click.echo("\n📂 文件类型分布:")
            for key, count in type_dist.items():
                name = type_names.get(key, key)
                click.echo(f"  {name}: {count} 个")

    except Exception as e:
        click.echo(f"❌ 获取统计信息失败: {str(e)}", err=True)


@cli.command()
@click.argument('prefix')
@click.argument('max_number', type=int)
@click.option('--db-path', type=click.Path(), help='数据库文件路径', default='duplicate_checker.db')
@click.option('--output', '-o', type=click.Path(), help='输出结果到文件')
@click.option('--limit', type=int, help='限制输出数量')
def find_missing(prefix: str, max_number: int, db_path: str, output: str, limit: int):
    """查找指定前缀缺失的序号"""
    try:
        with DatabaseDuplicateDetector(db_path) as db_detector:
            missing = db_detector.find_missing_numbers(prefix, max_number)

        if not missing:
            click.echo(f"\n✅ 前缀 '{prefix.upper()}' 的序号 1-{max_number} 全部存在。")
            return

        total = len(missing)
        display = missing[:limit] if limit else missing

        click.echo(f"\n🔍 发现 {total} 个缺失序号:")
        for i in range(0, len(display), 10):
            click.echo("  " + ", ".join(display[i:i + 10]))

        if limit and total > limit:
            click.echo(f"  ... 还有 {total - limit} 个")

        if output:
            with open(output, 'w', encoding='utf-8') as f:
                f.write("\n".join(missing))
            click.echo(f"\n📄 完整结果已保存到: {output}")

    except Exception as e:
        click.echo(f"❌ 查找失败: {str(e)}", err=True)


@db.command()
@click.argument('input_file', type=click.Path(exists=True))
@click.option('--db-path', type=click.Path(), help='数据库文件路径', default='duplicate_checker.db')
def import_data(input_file: str, db_path: str):
    """从文件导入数据到数据库"""
    try:
        with DatabaseDuplicateDetector(db_path) as db_detector:
            result = db_detector.import_file_to_database(input_file)

        if result['success']:
            click.echo(f"\n✅ 导入完成!")
            click.echo(f"总处理: {result['total_processed']}, 成功导入: {result['imported_count']}, 已存在: {result['existing_count']}, 脏数据: {result['dirty_count']}")
            if result['failed_count'] > 0:
                click.echo(f"导入失败: {result['failed_count']} 个")
        else:
            click.echo(f"❌ 导入失败: {result['error']}")

    except Exception as e:
        click.echo(f"❌ 导入失败: {str(e)}", err=True)


cli.add_command(db)

if __name__ == '__main__':
    cli()
